package com.zlx.mall.basic.common.holder;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.function.Function;

/**
 * Create a new SpringValidatorAdapter for the given JSR-303 Validator.
 * 默认响应文案参考hibernate.ValidationMessages_zh_CN.properties
 *
 * @author qingke
 **/
@Component
public class ValidatorHolder implements ApplicationContextAware {

    private static Validator validator;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext ctx) throws BeansException {
        Validator validatorBean = ctx.getBean(Validator.class);
        if (validatorBean instanceof LocalValidatorFactoryBean) {
            ValidatorHolder.validator = ((LocalValidatorFactoryBean) validatorBean).getValidator();
        } else if (validatorBean instanceof SpringValidatorAdapter) {
            ValidatorHolder.validator = validatorBean.unwrap(Validator.class);
        } else {
            ValidatorHolder.validator = validatorBean;
        }
    }

    public static <T, E extends RuntimeException> void validate(
            T object, Function<String, ? extends E> cause) {

        if (object == null) {
            throw cause.apply("{javax.validation.constraints.NotNull.message}");
        }

        for (ConstraintViolation<T> violation : validator.validate(object, Default.class)) {
            // fail fast
            throw cause.apply(violation.getMessage());
        }
    }
}
